import React from "react";

/**
 * reducer-callback to create reducer
 * @param stateObj current state-obj
 * @param action update operator
 * @returns reduce-updator
 */
function reducer(stateObj: Record<string, any>, action: { type: string, payload: any }) {
    return action.payload;
}

/**
 * global-state context
 */
const ctx = React.createContext({
    stateObj: {},
    update: (updator: Record<string, any>) => { }
});

/**
 * create initial-values of Provider-Component
 * @param globalState global-state object
 * @returns Initial-values of Provider-Component
 */
function initialValue(globalState: Record<string, any>) {
    const [stateObj, dispatch] = React.useReducer(reducer, globalState)
    const update = (updator: Record<string, any>) => { dispatch({ type: "", payload: updator }) }
    return { stateObj, update };
}

/**
 * Props of StateObjectProvider
 */
export interface StateObjectProviderProps {
    globalState: Record<string, any>
    children: React.ReactNode | undefined;
}

/**
 * StateObjectProvider-Component
 * @param props properties
 * @returns StateObjectProvider-Component
 */
export function StateObjectProvider(props: StateObjectProviderProps) {
    return (
        <ctx.Provider value={initialValue(props.globalState)}>
            {props.children}
        </ctx.Provider>
    )
}

export default ctx;